package com.example.demo.service;

import com.example.demo.entity.Book;
import com.example.demo.entity.BookType;
import com.example.demo.repository.BookRepository;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// 目前只支持xls文件格式传输
@Service
public class BookService {

    private static final Logger logger = LoggerFactory.getLogger(BookService.class);

    @Autowired
    private BookRepository bookRepository;

    @Autowired
    private BookTypeService bookTypeService;

    // 实现文件导入功能
    public void importBooksFromExcel(MultipartFile file) throws IOException {
        logger.info("filessssssss-------", file);
        if (file == null) {
            throw new IllegalArgumentException("File must not be null");
        }

        try (InputStream inputStream = file.getInputStream()) {
            if (inputStream == null) {
                throw new IllegalArgumentException("InputStream must not be null");
            }

            Workbook workbook = null;

            if (file.getOriginalFilename().endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(inputStream);
            } else if (file.getOriginalFilename().endsWith(".xls")) {
                workbook = new HSSFWorkbook(inputStream);
            }

            if (workbook == null) {
                throw new IllegalArgumentException("Workbook must not be null");
            }

            Sheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                throw new IllegalArgumentException("Sheet at index 0 must not be null");
            }

            // 继续处理 sheet
            List<Book> books = parseSheet(sheet);

            bookRepository.saveAll(books);

        } catch (Exception e) {
            logger.error("This is an info message", e);
        }
    }

    // 把excel表转换成book对象
    private List<Book> parseSheet(Sheet sheet) {
        // 解析 sheet 的逻辑
        List<Book> books = new ArrayList<>();
        // 假设第一行为标题，从第二行开始读取数据
        for (Row row : sheet) {
            if (row.getRowNum() == 0) {
                continue; // Skip header row
            }

            String bookName = getCellValue(row.getCell(0));
            String isbn = getCellValue(row.getCell(2));
            if (bookRepository.existsByName(bookName) || bookRepository.existsByIsbn(isbn)) {
                continue; // Skip existing book names
            }

            String bookTypeName = getCellValue(row.getCell(5));
            Optional<BookType> bookType = bookTypeService.findByName(bookTypeName);

            Book book = new Book();
            book.setName(bookName);
            book.setImageUrl(getCellValue(row.getCell(1)));
            book.setIsbn(isbn);
            book.setAuthor(getCellValue(row.getCell(3)));
            book.setDate(getCellValue(row.getCell(4)));
            book.setTypeId(bookType.get().getBookTypeId());
            // book.setFileUrl(getCellValue(row.getCell(6)));
            // book.setStatus(Integer.parseInt(getCellValue(row.getCell(7))));
            // book.setReadCount(Long.parseLong(getCellValue(row.getCell(8))));
            // book.setLoveCount(Long.parseLong(getCellValue(row.getCell(9))));
            // book.setBorrowStatus(Integer.parseInt(getCellValue(row.getCell(10))));
            // book.setPublishDate(Date.valueOf(getCellValue(row.getCell(6))));
            book.setDscript(getCellValue(row.getCell(7)));
            books.add(book);
        }
        return books;
    }

    // 获取excel单元格的值
    private String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    return String.valueOf(cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }

    // 分页读取书本列表
    public Page<Book> getBooks(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return bookRepository.findAll(pageable);
    }

    // 获取 book 表尾部 20 条数据
    public List<Book> getTailBooks() {
        // 获取总记录数
        long totalBooks = bookRepository.count();

        // 计算最后一页的页码
        int page = (int) ((totalBooks - 1) / 20); // 每页 20 条数据
        // 创建分页对象
        Pageable pageable = PageRequest.of(page, 20); // 按创建时间倒序排序
        // 查询最后一页数据
        Page<Book> bookPage = bookRepository.findAll(pageable);
        return bookPage.getContent();
    }

    // 根据 id 查询书本信息
    public Book getBookById(Integer bookId) {
        Optional<Book> optionalBook = bookRepository.findById(bookId);
        if (optionalBook.isPresent()) {
            return optionalBook.get();
        } else {
            throw new IllegalArgumentException("Book with ID " + bookId + " not found");
        }
    }

    // 保存单个书本对象
    public Book saveBook(Book book) {
        return bookRepository.save(book);
    }

    // 更新书本的 fileUrl 属性
    public Book updateBookFileUrl(int bookId, String fileUrl) {
        Optional<Book> optionalBook = bookRepository.findById(bookId);
        if (optionalBook.isPresent()) {
            Book book = optionalBook.get();
            book.setFileUrl(fileUrl);
            return bookRepository.save(book);
        } else {
            throw new IllegalArgumentException("Book with ID " + bookId + " not found");
        }
    }

    // 更新书本的 bookType 属性
    public Book updateBookType(int bookId, int bookType) {
        Optional<Book> optionalBook = bookRepository.findById(bookId);
        if (optionalBook.isPresent()) {
            Book book = optionalBook.get();
            book.setTypeId(bookType);
            return bookRepository.save(book);
        } else {
            throw new IllegalArgumentException("Book with ID " + bookId + " not found");
        }
    }

    // 更新书本的 bookType 属性
    public Book updateBookStatus(int bookId, int status) {
        Optional<Book> optionalBook = bookRepository.findById(bookId);
        if (optionalBook.isPresent()) {
            Book book = optionalBook.get();
            book.setStatus(status);
            return bookRepository.save(book);
        } else {
            throw new IllegalArgumentException("Book with ID " + bookId + " not found");
        }
    }

    // 添加模糊搜索方法
    public Page<Book> searchBooksByName(String name, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return bookRepository.findByNameContaining(name, pageable);
    }
}